// pages/imagePreview/preview.js
const app = getApp();
const http = require('../../utils/http.js');

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		id: null,
		se_no: null,
		se_title: '',
		starttime: '',
		pic_num: 0,

		// 卡片模块：
		currentIndex: 0, //预设当前项的值
		scrollLeft: 0, //切换栏的滚动条位置
		cardImgSrc: '', //存储卡片图
		//卡片数组
		imgList: [],
		isMask: false


	},
	getList(id) {
		http.post('api/session/se_pictures', {
			id
		}, 1).then(res => {
			if (res.data.city) {
				wx.setNavigationBarTitle = res.data.city + '赛区'
			}
			this.setData({
				imgList: res.data.pic_list,
				pic_num: res.data.pic_num,
				se_no: res.data.se_no,
				se_title: res.data.se_title,
				starttime: res.data.starttime
			})
		})
	},
	swiperChange(e) {
		this.setData({
			currentIndex: e.detail.current
		});
		console.log(this.data.currentIndex)
	},

	// 点击切换当前页时改变样式
	swichNav: function(e) {
		var that = this,
			cur = e.target.dataset.current,
			src = e.target.dataset.src;
		if (that.data.currentIndex == cur) {
			return false;
		} else {
			that.setData({
				currentIndex: cur
			})
		}
		that.setData({
			cardImgSrc: src
		})
		that.checkCor();
	},
	//判断当前滚动超过一屏时
	checkCor: function(e) {
		var that = this;
		if (that.data.currentIndex > 4) {
			that.setData({
				scrollLeft: 300
			})
		} else {
			that.setData({
				scrollLeft: 0
			})
		}
	},
	//保存图片
	saveImage() {
		const that = this;
		// 检查授权状态
		wx.getSetting({
			success(res) {
				if (!res.authSetting['scope.writePhotosAlbum']) {
					// 如果没有授权，则请求授权
					wx.authorize({
						scope: 'scope.writePhotosAlbum',
						success() {
							that.downloadAndSaveImage();
						},
						fail() {
							wx.showModal({
								title: '授权失败',
								content: '您拒绝了保存到相册的授权，将无法正常使用该功能。',
								showCancel: false
							});
						}
					});
				} else {
					// 如果已经授权，则直接下载并保存图片
					that.downloadAndSaveImage();
				}
			}
		});
	},
	downloadAndSaveImage: app.debounce(function() {
		const that = this;
		var img = that.data.imgList[that.data.currentIndex];
		wx.showLoading({
			title: '保存图片中…',
			mask: true
		})
		that.setData({
			isMask: true
		})
		// 下载图片
		wx.downloadFile({
			url: img,
			success(res) {
				if (res.statusCode === 200) {
					// 下载成功，保存图片到相册
					wx.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success() {
							wx.showToast({
								title: '保存成功'
							});
							that.setData({
								isMask: false
							})
						},
						fail() {
							wx.showToast({
								title: '保存失败',
								icon: 'none'
							});
							that.setData({
								isMask: false
							})
						}
					});
				}
			},
			fail() {
				wx.showToast({
					title: '图片下载失败',
					icon: 'none'
				});
				that.setData({
					isMask: false
				})
			}
		});
	},900),
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		//卡片默认显示第一张
		this.setData({id:options.id})
		this.getList(options.id)

	},
	goPath(e) {
		wx.navigateTo({
			url: e.currentTarget.dataset.url,
		})
	},
})